package com.leizhe.yitao.yitaosellerservice.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.github.pagehelper.PageInfo;
import com.leizhe.yitao.bo.BrandBo;
import com.leizhe.yitao.common.exception.ServiceException;
import com.leizhe.yitao.domain.Brand;
import com.leizhe.yitao.domain.Category;
import com.leizhe.yitao.domain.User;
import com.leizhe.yitao.entity.PageResult;
import com.leizhe.yitao.mapper.BrandMapper;
import com.leizhe.yitao.upload.service.BrandService;
import com.github.pagehelper.PageHelper;
import com.leizhe.yitao.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.rmi.ServerException;
import java.util.Date;
import java.util.List;

/**
 * 品牌业务处理类
 */
@Service(timeout = 3000)
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;


    @Reference(
            timeout = 50000,
            retries = -1,
            check = false,
            registry = "${dubbo.registry.address}")
    private UserService userService;


    // @Autowired
    @Reference(
            timeout = 50000,
            retries = -1,
            check = false,
            registry = "${dubbo.registry.address}")
    private BrandService brandService;

    @Override
    @LcnTransaction
    public void add() {
        // 新增商品
        Brand brand = new Brand();
        brand.setName("艾特吗");
        brand.setImage("http://yitao.image.com/group1/M00/00/00/wKjRgV5xm1WAaemgAAATYLwwViE410.jpg");
        brand.setLetter(new Character('J'));
        brandService.addBrand(brand);
        if (true){
            throw new ServiceException("模拟报错");
        }


        User user = new User();

        user.setUsername("zzzzzz");
        user.setPassword("zzzzzzzz");
        user.setPhone("13007610305");
        user.setCreated(new Date());
        user.setSalt("aaaaaaa");


        userService.add(user);



    }




    /**
     * 品牌查询
     * @param page 当前页码
     * @param rows 当前行数
     * @param sortBy 根据对应字段排序
     * @param desc 是否倒序排序
     * @param key 查询条件
     * @return
     */
    @Override
    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows, String sortBy, Boolean desc, String key) {

        Example example = new Example(Brand.class);

        // 查询条件
        if (StringUtils.isNotBlank(key)){
            example.createCriteria().orLike("name","%"+key+"%").orEqualTo("letter",key);
        }
        // 是否进行排序
        if (StringUtils.isNotBlank(sortBy)) {
            example.setOrderByClause(sortBy + (desc? " DESC" : "  ASC"));
        }
        // 如果行数小于0，那么展示所有的行数
        if (rows < 0){
            rows = brandMapper.selectCountByExample(example);
        }

        // 进行查询
        PageHelper.startPage(page,rows);
        List<Brand> brandList = brandMapper.selectByExample(example);

        // 如果未查出数据，报异常
        if (CollectionUtils.isEmpty(brandList)){
            throw new ServiceException("查询的品牌列表为空");
        }

        PageInfo<Brand> pageInfo = new PageInfo<>(brandList);
        return new PageResult<>(pageInfo.getTotal(),brandList);
    }



    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        brand.setId(null);
        int resultCount = brandMapper.insert(brand);
        if (resultCount == 0) {
            throw new ServiceException("保存品牌失败");
        }
        //更新品牌分类表
        for (Long cid : cids) {
            resultCount = brandMapper.saveCategoryBrand(cid, brand.getId());

            if (resultCount == 0) {
                throw new ServiceException("更新的品牌分类失败");
            }
        }
    }

    @Override
    public List<Category> queryCategoryByBid(Long bid) {
        return brandMapper.queryCategoryByBid(bid);
    }

    @Transactional
    @Override
    public void updateBrand(BrandBo brandBo) {
        Brand brand = new Brand();
        brand.setId(brandBo.getId());
        brand.setName(brandBo.getName());
        brand.setImage(brandBo.getImage());
        brand.setLetter(brandBo.getLetter());

        //更新
        int resultCount = brandMapper.updateByPrimaryKey(brand);
        if (resultCount == 0) {
            throw new ServiceException("更新的品牌失败");
        }
        List<Long> cids = brandBo.getCids();
        //更新品牌分类表
        brandMapper.deleteCategoryBrandByBid(brandBo.getId());

        for (Long cid : cids) {
            resultCount = brandMapper.saveCategoryBrand(cid, brandBo.getId());
            if (resultCount == 0) {
                throw new ServiceException("更新的品牌分类失败");
            }
        }
    }

    @Transactional
    @Override
    public void deleteBrand(Long bid) {
        int result = brandMapper.deleteByPrimaryKey(bid);
        if (result == 0) {
            throw new ServiceException("删除品牌失败");
        }
        //删除中间表
        result = brandMapper.deleteCategoryBrandByBid(bid);
        if (result == 0) {
            throw new ServiceException("删除品牌和分类之间关系失败");
        }
    }

    @Override
    public List<Brand> queryBrandByCid(Long cid) {
        List<Brand> brandList = brandMapper.queryBrandByCid(cid);
        if (CollectionUtils.isEmpty(brandList)) {
            throw new ServiceException("没有找到分类下的品牌");
        }
        return brandList;
    }

    @Override
    public Brand queryBrandByBid(Long id) {
        Brand brand = new Brand();
        brand.setId(id);
        Brand b1 = brandMapper.selectByPrimaryKey(brand);
        if (b1 == null) {
            throw new ServiceException("查询品牌不存在");
        }
        return b1;
    }

    @Override
    public List<Brand> queryBrandByIds(List<Long> ids) {
        List<Brand> brands = brandMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(brands)) {
            throw new ServiceException("查询品牌不存在");
        }
        return brands;
    }

    @Override
    @LcnTransaction
    public void addBrand(Brand brand) {
        int resultCount = brandMapper.insert(brand);
    }



}
